package eu.news.interconnect.server;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import eu.jk.web.kits.ClientAnalyst;
import eu.news.interconnect.Message;

/**
 * Servlet implementation class ServerReceiver
 */
public class ServerListener extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServerListener() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Message message = Message.rebuild(request.getInputStream());
		if (message == null){
			response.sendError(400);
			return;
		}
		Message responseMessage = null;
		String ip=ClientAnalyst.getIpAddr(request);
		int authResult = Authenticator.check(message, ip);
		if (authResult>0){
			responseMessage = new Message(Message.TYPE.ERROR_INFO, null);
			responseMessage.setRemark("you have no authority to perform this operation");
			response.getOutputStream().write(responseMessage.getSerializeBytes());
			return;
		}
		Delegater delegater = ActionDispatch.getDelegater(message);
		if (delegater==null){
			// 返回错误信息
			responseMessage = new Message(Message.TYPE.ERROR_INFO, null);
			responseMessage.setRemark("No suitable message processor found,check your message");
		} else {
			responseMessage = delegater.doJobs(message);
		}
		if(responseMessage == null){
			// 返回错误信息
			responseMessage = new Message(Message.TYPE.ERROR_INFO, null);
			responseMessage.setRemark("message processor return no message," +
					"some thing must be error");
		}
		response.getOutputStream().write(responseMessage.getSerializeBytes());
	}

//	private String doNews(NewsEntity ne,Interface face){
//		SortDAO sDao = new SortDAO();
//		Sort sort = null;
//		for(Sort s:sDao.getByName(ne.getSort())){
//			if(s.getSpecial().getName().equals(ne.getSpecial())){
//				sort=s;
//				break;
//			}
//		}
//		if(sort==null)
//			return "未找到指定分类，拒绝请求。";
//		OperatorDAO opDao=new OperatorDAO();
//		Operator operator=opDao.getByName(ne.getOperator());
//		if(operator==null)
//			operator=new Operator(ne.getOperator(), Operator.TYPE.MARK_ONLY);
//		opDao.save(operator);
//		opDao.refresh(operator);
//		opDao.commit();
//		News news=new News(ne.getTitle(), sort, operator);
//		news.setTime(ne.getTime());
//		news.setContent(ne.getContent());
//		news.setState(News.State.STATE_PUBLISHED);
//		NewsDAO nDao=new NewsDAO();
//		nDao.save(news);
//		nDao.commit();
//		return null;
//	}
	
}
